package com.google.code.irouter.portal.client.dashboard.main.center.managers.library.browser;

import java.util.ArrayList;
import java.util.List;

import com.google.code.irouter.portal.client.AppConstants;
import com.google.code.irouter.portal.client.dashboard.main.center.managers.library.browser.guide.Command;
import com.google.code.irouter.portal.client.dashboard.main.center.managers.library.browser.guide.command.Tag;
import com.google.code.irouter.portal.client.rpc.guide.GuideResult;
import com.google.code.irouter.portal.client.rpc.guide.GuideService;
import com.google.code.irouter.portal.client.rpc.guide.GuideServiceAsync;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.gwtext.client.core.Ext;
import com.gwtext.client.core.SortDir;
import com.gwtext.client.data.ArrayReader;
import com.gwtext.client.data.FieldDef;
import com.gwtext.client.data.GroupingStore;
import com.gwtext.client.data.MemoryProxy;
import com.gwtext.client.data.Record;
import com.gwtext.client.data.RecordDef;
import com.gwtext.client.data.SortState;
import com.gwtext.client.data.StringFieldDef;
import com.gwtext.client.widgets.grid.ColumnConfig;
import com.gwtext.client.widgets.grid.ColumnModel;
import com.gwtext.client.widgets.grid.GridPanel;
import com.gwtext.client.widgets.grid.GroupingView;

public final class Guide extends GridPanel {

	private static final AppConstants CONSTANTS = GWT.create(AppConstants.class);
	
	private final GuideServiceAsync guideService = GWT.create(GuideService.class);

	public Guide() {
		super();
		this.setId(Guide.class.getName());

		RecordDef recordDef = new RecordDef(  
                new FieldDef[]{  
                        new StringFieldDef("name"),  
                        new StringFieldDef("detector"),  
                        new StringFieldDef("resource"),  
                        new StringFieldDef("fixedLink"),
                        new StringFieldDef("createDate"),                          
                        new StringFieldDef("updateDate"),
                        new StringFieldDef("key")
                }  
        );  

        MemoryProxy proxy = new MemoryProxy(new Object[0][0]);  
  
        ArrayReader reader = new ArrayReader(recordDef);  
        GroupingStore store = new GroupingStore();  
        store.setReader(reader);  
        store.setDataProxy(proxy);  
        store.setSortInfo(new SortState("name", SortDir.ASC));  
        store.setGroupField("detector");
        store.load();  
        this.setStore(store);  
  
  
        ColumnConfig[] columns = new ColumnConfig[]{  
                new ColumnConfig(
                		CONSTANTS.com_google_code_irouter_portal_client_dashboard_main_center_managers_library_browser_guide_column_name(), 
                		"name", 
                		160,
                		true, 
                		null, 
                		"target"
                ),  
                new ColumnConfig(
                		CONSTANTS.com_google_code_irouter_portal_client_dashboard_main_center_managers_library_browser_guide_column_detector(), 
                		"detector", 
                		160,
                		true
                ),  
                new ColumnConfig(
                		CONSTANTS.com_google_code_irouter_portal_client_dashboard_main_center_managers_library_browser_guide_column_resource(), 
                		"resource", 
                		160,
                		false
                ),  
                new ColumnConfig(
                		CONSTANTS.com_google_code_irouter_portal_client_dashboard_main_center_managers_library_browser_guide_column_fixedLink(), 
                		"fixedLink", 
                		160,
                		false
                ),  
                new ColumnConfig(
                		CONSTANTS.com_google_code_irouter_portal_client_dashboard_main_center_managers_library_browser_guide_column_create(), 
                		"createDate", 
                		150,
                		false
                ),  
                new ColumnConfig(
                		CONSTANTS.com_google_code_irouter_portal_client_dashboard_main_center_managers_library_browser_guide_column_update(), 
                		"updateDate", 
                		150,
                		false
                ) 
        };  
  
        ColumnModel columnModel = new ColumnModel(columns);  
        this.setColumnModel(columnModel);
        this.setStripeRows(true);  
        this.setAutoExpandColumn("name");
        this.setTopToolbar(new Command());
        
        GroupingView gridView = new GroupingView();  
        gridView.setForceFit(true);  
        gridView.setGroupTextTpl("{text} ({[values.rs.length]} {[values.rs.length > 1 ? \"Items\" : \"Item\"]})");  
        this.setView(gridView);  
        this.setAnimCollapse(false);
        this.addGridRowListener(new GuideListener());
        this.setBorder(false);
	}

	public void remove() {
		getEl().mask(CONSTANTS.com_google_code_irouter_portal_client_common_processing(), true);
		Record[] records = getSelectionModel().getSelections();
		if(records.length > 0) {
			final List<String> idList = new ArrayList<String>();
			for(Record record : records) {
				idList.add(record.getAsString("key"));				
			}		
			guideService.remove(
					idList.toArray(new String[0]), 
					new AsyncCallback<Boolean>() {
						public void onFailure(Throwable caught) {
						// TODO
							getEl().unmask();
						}
		
						public void onSuccess(Boolean result) {
							refresh();
							getEl().unmask();
						}
					}
				);
		} else {
			getEl().unmask();
		}
	}
	
	public void reset() {
		RecordDef recordDef = new RecordDef(  
                new FieldDef[]{  
                        new StringFieldDef("name"),  
                        new StringFieldDef("detector"),  
                        new StringFieldDef("resource"),  
                        new StringFieldDef("fixedLink"),
                        new StringFieldDef("createDate"),                          
                        new StringFieldDef("updateDate"),
                        new StringFieldDef("key")
                }  
        );  

        MemoryProxy proxy = new MemoryProxy(new Object[0][0]);  
  
        ArrayReader reader = new ArrayReader(recordDef);  
        GroupingStore store = new GroupingStore();  
        store.setReader(reader);  
        store.setDataProxy(proxy);  
        store.setSortInfo(new SortState("name", SortDir.ASC));  
        store.setGroupField("detector");
        store.load();
        
		reconfigure(store, getColumnModel());
	}

	public void refresh() {
		getEl().mask(CONSTANTS.com_google_code_irouter_portal_client_common_processing(), true);
		Tag tag = (Tag) Ext.getCmp(Tag.class.getName());
		guideService.load(
				tag.getText(),
				new AsyncCallback<List<GuideResult>>() {
					public void onFailure(Throwable caught) {
					// TODO
						reset();
						getEl().unmask();
					}

					public void onSuccess(List<GuideResult> guideResultList) {
						if(guideResultList != null) {
							Object[][] guideArray = new Object[guideResultList.size()][7];
							int index = 0;
							for (GuideResult guideResult : guideResultList) {
								Object[] guideItem = new Object[7];
								guideItem[0] = guideResult.getName();
								guideItem[1] = guideResult.getDetector();
								guideItem[2] = guideResult.getResource();
								guideItem[3] = guideResult.getFixedLink();
								guideItem[4] = guideResult.getCreateDate();
								guideItem[5] = guideResult.getUpdateDate();
								guideItem[6] = String.valueOf(guideResult.getId());
								guideArray[index] = guideItem;
								index++;
							}						
							RecordDef recordDef = new RecordDef(  
					                new FieldDef[]{  
					                        new StringFieldDef("name"),  
					                        new StringFieldDef("detector"),  
					                        new StringFieldDef("resource"),  
					                        new StringFieldDef("fixedLink"),
					                        new StringFieldDef("createDate"),                          
					                        new StringFieldDef("updateDate"),
					                        new StringFieldDef("key")
					                }  
					        );  
	
					        MemoryProxy proxy = new MemoryProxy(guideArray);  
					  
					        ArrayReader reader = new ArrayReader(recordDef);  
					        GroupingStore store = new GroupingStore();  
					        store.setReader(reader);  
					        store.setDataProxy(proxy);  
					        store.setSortInfo(new SortState("name", SortDir.ASC));  
					        store.setGroupField("detector");
					        store.load();
					        
							reconfigure(store, getColumnModel());
						} else {
							reset();							
						}
						getEl().unmask();
					}
				}
		);
	}
}
